#ifndef _SESSION_MANAGER_H_
#define _SESSION_MANAGER_H_

#include "Define.h"
#include <map>
#include <vector>
#include <deque>
#include "Header.h"
#include "ConnSession.h"

class CSessionBase;
class CSessionManager
{
    SINGLETON_CLASS_DEFINE(CSessionManager);

public:
    void AddSession(u64 id, CSessionBase *session, bool needCheckAlive=false);
    void RemoveSession(u64 id);

    void AddRpcServer(u64 sid, const char *ip, s32 port, SGLib::IPacketParser *parser);
    void RpcConnect(u64 sid);                            // start to connect
    void RpcConnected(u64 sid, SGLib::CIoSocketEx *rpc); // need call after connect success
    void RpcClosed(u64 sid);                             // need call after connection close

    void AddServer(u64 id, CSessionBase *server);
    void RemoveServer(u64 id);

    CSessionBase* FindSession(u64 id);
    CConnSession* FindRpcServer(u64 id);
    CSessionBase* FindServer(u64 id);

    s32 SessionCount();
    void CheckSessionAlive();
    void DumpSessions(std::vector<CSessionBase*> &sessions);
    void DumpServers(std::vector<CSessionBase*> &servers);
    void DumpRpcServers(std::vector<CConnSession*> &rpcServers);

private:
    void _PushCheckQueue(u64 sid);
    bool _PopCheckQueue(u64 &sid);

private:
    // <sessionid, clients> 
    std::map<u64, CSessionBase*> m_sessions;    // accept sessions 
    // <serverid, rpcServers>
    std::map<u64, CConnSession*> m_rpcServers;   // connect servers
    // <serverid, servers>
    std::map<u64, CSessionBase*> m_servers;     // accept servers 

    std::deque<u64> m_checkQueue;
};

#endif

